import { useEffect } from "react";

import useSetState from "./useSetState";

export default function useReq<T = any>(request: () => Promise<T>, deps: any[] = []) {
  const [{ data, loading }, setState] = useSetState({
    data: undefined as T,
    loading: false
  })
  const run = async () => {
    setState({ loading: true })
    try {
      const res = await request()
      setState({ data: res })
    } catch (error) { /* empty */ }

    setState({ loading: false })
  }
  useEffect(() => {
    run()

  }, deps)

  return { data, loading, run }
}